from flask import (
    Blueprint,
    request,
    g,
    redirect,
    url_for
)

from exit import db
from decimal import Decimal
from datetime import datetime, date, timedelta
from apps.api.decorators import login_required, login_need
from .forms import *
from .decorators import *
from apps.api.forms import UploadImgForm
from .models import *
from apps.api.models import *
from apps.common.models import *
from utils import restful, api_util, common_util, deliver_api
from sqlalchemy import func, or_
import requests
import json
from shortuuid import uuid
from .views_mall import bp


@bp.route('/sell_batch_freeze/')    # 可转冻结批次
@login_required
def sell_batch_freeze():
    page = request.args.get('page', default=1, type=int)
    pages = (page - 1) * 20
    bath = BuyDeal.query.filter(
        BuyDeal.buyer_id == g.user.id, BuyDeal.t_type == 1, BuyDeal.status == 0,
        (BuyDeal.s_num - BuyDeal.s_num_sell) > 0,
    ).order_by(BuyDeal.create_time).limit(20).offset(pages)
    bath_list = list()
    for i in bath:
        bath_info = i.buy_deal_json()
        bath_info['s_num'] = i.s_num - i.s_num_sell
        bath_info['status_str'] = '冻结票'
        bath_list.append(bath_info)

    data_dict = dict()
    data_dict['bath_list'] = bath_list
    return restful.success(data=data_dict)


@bp.route('/seller_transfer_order/', methods=['POST'])    # 卖家冻结转让
@login_required
def seller_transfer_order():
    t_type = request.form.get('t_type', default=1)
    t_type = int(t_type)
    if t_type == 1:
        if g.user.status != 2:
            return restful.params_error(message='未实名不能交易')
    # time_required = api_util.trade_time_required(0)
    # time_required2 = api_util.trade_time_required(5)
    # if time_required is False and time_required2 is False:
    #     return restful.params_error(message='当前时间未开放！')
    try:
        phone = request.form.get('phone')
        num = request.form.get('num')
        bath_id = request.form.get('bath_id')
        price = request.form.get('price')
        # print(price, '价格')
        num = int(num)

        other_user = User.query.filter_by(phone=phone).first()
        if other_user is None:
            return restful.params_error(message='未找到用户')
        if phone == g.user.phone:
            return restful.params_error(message='不能转给自己')
        if t_type == 1:
            if num < 2:
                return restful.params_error(message='数量请输入2的倍数')

            if num % 2 != 0:
                return restful.params_error(message='数量请输入2的倍数')

        buy_deal = BuyDeal.query.filter_by(id=bath_id, buyer_id=g.user.id).with_for_update().first()
        if buy_deal is None:
            return restful.params_error(message='未找到可卖批次')
        if buy_deal.s_num - buy_deal.s_num_sell < num:
            return restful.params_error(message='剩余转让数量不足')
        if t_type == 2:
            global_transfer_sell = GlobalParams.get_params(11)
            if g.user.income < global_transfer_sell * num:
                return restful.params_error(message='可用资产不足')
            g.user.income -= (global_transfer_sell * num)
            api_util.user_record(
                user_id=g.user.id, r_label=1, r_type=10, r_state=2,
                num=(global_transfer_sell * num), r_wallet=1,
                order_id=buy_deal.id
            )

        if t_type == 1:
            buy_deal.s_num -= int(num / 2)
            # 价格
            global_transfer_price = GlobalParams.get_params(8)
            total_money = global_transfer_price * num
            price = global_transfer_price
        else:
            buy_deal.s_num -= num
            # 价格
            price = Decimal(price)
            if price < 0:
                return restful.params_error(message='价格输入错误')
            total_money = price * num

            # print(price, total_money)
        create_transfer = TransferOrder(
            user_id=g.user.id, to_user_id=other_user.id,
            goods_id=buy_deal.goods_id, batch_id=buy_deal.id,
            status=0, t_type=t_type, num=num,
            price=price, total_money=total_money
        )
        db.session.add(create_transfer)
        db.session.commit()

        return restful.success()
    except Exception as e:
        print(e)
        db.session.close()
        return restful.params_error(message='网络错误请重试！')


@bp.route('/del_transfer_order/', methods=['POST'])  # 取消转让订单
@login_required
def del_transfer_order():
    # time_required = api_util.trade_time_required(0)
    # time_required2 = api_util.trade_time_required(5)
    # if time_required is False and time_required2 is False:
    #     return restful.params_error(message='当前时间未开放！')
    order_id = request.form.get('order_id')
    transfer_order = TransferOrder.query.filter_by(id=order_id, user_id=g.user.id, status=0).with_for_update().first()
    if transfer_order is None:
        return restful.params_error(message='未找到订单')

    buy_deal = BuyDeal.query.filter_by(id=transfer_order.batch_id, buyer_id=g.user.id).with_for_update().first()
    if buy_deal is None:
        return restful.params_error(message='未找到冻结单')

    transfer_order.status = 2
    transfer_order.update_time = datetime.now()

    if transfer_order.t_type == 1:
        buy_deal.s_num += transfer_order.num / 2  # 返还批次数量
    else:
        buy_deal.s_num += transfer_order.num  # 返还批次数量
        global_transfer_sell = GlobalParams.get_params(11)
        g.user.income += (global_transfer_sell * transfer_order.num)
        api_util.user_record(
            user_id=g.user.id, r_label=1, r_type=11, r_state=1,
            num=(global_transfer_sell * transfer_order.num), r_wallet=1,
            order_id=buy_deal.id
        )

    db.session.commit()
    return restful.success()


@bp.route('/transfer_order_record/', methods=['POST'])     # 转让记录
@login_required
def transfer_order_record():
    page = request.form.get('page', type=int, default=1)
    pages = (page - 1) * 20
    t_type = request.form.get('t_type', type=int)
    r_type = request.form.get('r_type', type=int, default=1)
    filters = list()
    filters.append(TransferOrder.status == 0)
    filters.append(TransferOrder.t_type == r_type)
    if t_type == 1:
        filters.append(TransferOrder.user_id == g.user.id)
    else:
        filters.append(TransferOrder.to_user_id == g.user.id)

    transfer_order = TransferOrder.query.filter(*filters).order_by(TransferOrder.create_time.desc()).limit(
            20).offset(pages)
    order_list = list()

    for i in transfer_order:
        order_json = i.transfer_order_json()
        order_json['price'] = 0
        order_json['order_id'] = i.id
        order_json['num'] = Decimal(i.num)
        seller = User.query.filter_by(id=i.user_id).first()
        buyer = User.query.filter_by(id=i.to_user_id).first()
        order_json['seller_name'] = seller.real_name
        order_json['seller_phone'] = seller.phone
        order_json['buyer_name'] = buyer.real_name
        order_json['buyer_phone'] = buyer.phone
        # goods_list = list()
        goods = Goods.query.filter_by(id=i.goods_id).first()
        if goods:
            order_json['name'] = goods.name
            order_json['goods_code'] = goods.goods_code
        if i.user_id == g.user.id:
            order_json['status_str'] = '协议转出'
        else:
            order_json['status_str'] = '协议转入'
        order_list.append(order_json)

    order_dict = dict()
    order_dict['order_list'] = order_list
    return restful.success(data=order_dict)


@bp.route('/buyer_confirm/', methods=['POST'])      # 买家确认
@login_required
def buyer_confirm():
    try:
        # time_required = api_util.trade_time_required(0)
        # time_required2 = api_util.trade_time_required(5)
        # if time_required is False and time_required2 is False:
        #     return restful.params_error(message='当前时间未开放！')
        order_id = request.form.get('order_id')
        transfer_order = TransferOrder.query.filter_by(id=order_id, to_user_id=g.user.id, status=0).with_for_update().first()
        if transfer_order is None:
            return restful.params_error(message='未找到订单')
        # 买方手续费
        global_params_buy = GlobalParams.get_params(1)
        buy_fee = transfer_order.total_money * global_params_buy

        total_price_buy = transfer_order.total_money + buy_fee

        if g.user.income < total_price_buy:
            return restful.params_error(message='可用资金不足！')

        # 买家
        g.user.income -= total_price_buy
        api_util.user_record(user_id=g.user.id, r_label=1, r_type=8, r_state=2, num=transfer_order.total_money, r_wallet=1, order_id=transfer_order.id)
        # 买家手续费记录
        api_util.user_record(user_id=g.user.id, r_label=2, r_type=5, r_state=2, num=buy_fee, r_wallet=1, order_id=transfer_order.id)

        # 卖出价格拆分
        if transfer_order.t_type == 1:
            num = int(transfer_order.num / 2)
            deal_buy_fee = buy_fee / 2
        else:
            num = int(transfer_order.num)
            deal_buy_fee = buy_fee
        sell_total_price = num * transfer_order.price
        # 卖出手续费
        global_params_sell = GlobalParams.get_params(0)
        sell_fee = sell_total_price * global_params_sell

        # 卖家 加收益
        seller = User.query.filter_by(id=transfer_order.user_id).with_for_update().first()
        seller.income += (sell_total_price - sell_fee)

        api_util.user_record(user_id=seller.id, r_label=3, r_type=2, r_state=1, num=sell_total_price, r_wallet=1, order_id=transfer_order.id)
        # 卖出手续费记录
        api_util.user_record(user_id=seller.id, r_label=2, r_type=6, r_state=2, num=sell_fee, r_wallet=1, order_id=transfer_order.id)

        if transfer_order.t_type == 1:
            # 系统卖家
            system_user = User.query.filter_by(phone='15224897513').with_for_update().first()
            system_user.income += (sell_total_price - sell_fee)
            # 卖出记录
            api_util.user_record(user_id=system_user.id, r_label=3, r_type=2, r_state=1, num=sell_total_price, r_wallet=1, order_id=transfer_order.id)
            # 卖出手续费记录
            api_util.user_record(user_id=system_user.id, r_label=2, r_type=6, r_state=2, num=sell_fee, r_wallet=1, order_id=transfer_order.id)
            # 扣除系统账号批次
            system_buy_deal = BuyDeal.query.filter(
                BuyDeal.buyer_id == system_user.id, BuyDeal.t_type == 1, BuyDeal.status == 0,
                (BuyDeal.s_num - BuyDeal.s_num_sell) >= num,
            ).with_for_update().first()
            if system_buy_deal is None:
                return restful.params_error(message='确认失败')
            system_buy_deal.s_num -= num
            # 系统卖出批次
            create_deal_system = BuyDeal(
                sell_order_id=transfer_order.id, buy_order_id=transfer_order.id,
                buyer_id=g.user.id, seller_id=system_user.id,
                sell_batch_id=system_buy_deal.id, deal_num=num, deal_price=transfer_order.price,
                deal_type=4, deal_money=sell_total_price, s_num=num, s_num_sell=0, tn_day=0,
                goods_id=transfer_order.goods_id, buy_fee=deal_buy_fee, sell_fee=sell_fee,
                t_type=1
            )
            db.session.add(create_deal_system)

            # 买家买入明细记录
            api_util.user_record(
                user_id=g.user.id, r_label=10, r_type=17, r_state=1,
                num=num, r_wallet=1, order_id=transfer_order.id,
                r_coin=transfer_order.price, other_id=system_user.id
            )
            # 平台卖家转让明细记录
            api_util.user_record(
                user_id=system_user.id, r_label=10, r_type=18, r_state=2,
                num=num, r_wallet=1, order_id=transfer_order.id,
                r_coin=transfer_order.price, other_id=g.user.id
            )

        # 生成两条买家批次
        create_deal_seller = BuyDeal(
            sell_order_id=transfer_order.id, buy_order_id=transfer_order.id,
            buyer_id=g.user.id, seller_id=seller.id,
            sell_batch_id=transfer_order.batch_id, deal_num=num, deal_price=transfer_order.price,
            deal_type=4, deal_money=sell_total_price, s_num=num, s_num_sell=0, tn_day=0,
            goods_id=transfer_order.goods_id, buy_fee=deal_buy_fee, sell_fee=sell_fee,
            t_type=1
        )
        db.session.add(create_deal_seller)

        transfer_order.status = 1
        transfer_order.update_time = datetime.now()

        # 买家买入明细记录
        api_util.user_record(
            user_id=g.user.id, r_label=10, r_type=17, r_state=1,
            num=num, r_wallet=1, order_id=transfer_order.id,
            r_coin=transfer_order.price, other_id=seller.id
        )

        # 卖家转让明细记录
        api_util.user_record(
            user_id=seller.id, r_label=10, r_type=18, r_state=2,
            num=num, r_wallet=1, order_id=transfer_order.id,
            r_coin=transfer_order.price, other_id=g.user.id
        )

        db.session.commit()
        return restful.success()
    except Exception as e:
        print(e)
        db.session.close()
        return restful.params_error(message='网络错误请重试！')


@bp.route('/freeze_locking_deal/')    # 待释方和锁定列表
@login_required
def freeze_locking_deal():
    page = request.args.get('page', default=1, type=int)
    pages = (page - 1) * 20
    bath = BuyDeal.query.filter(
        BuyDeal.buyer_id == g.user.id,
        or_(BuyDeal.t_type == 2, BuyDeal.status == 1),
        BuyDeal.t_type != 1,
        BuyDeal.s_num > 0,
    ).order_by(BuyDeal.create_time).limit(20).offset(pages)
    bath_list = list()
    for i in bath:
        bath_info = i.buy_deal_json()
        bath_info['s_num'] = i.s_num
        if i.t_type == 2:
            bath_info['status_str'] = '待释放票'
        else:
            bath_info['status_str'] = '锁定票'
        bath_list.append(bath_info)

    data_dict = dict()
    data_dict['bath_list'] = bath_list
    return restful.success(data=data_dict)


@bp.route('/freeze_locking_transfer/', methods=['POST'])    # 待释放锁定转到冻结
@login_required
def freeze_locking_transfer():
    # if g.user.status != 2:
    #     return restful.params_error(message='未实名不能交易')
    try:
        num = request.form.get('num')
        bath_id = request.form.get('bath_id')
        num = int(num)

        buy_deal = BuyDeal.query.filter_by(id=bath_id, buyer_id=g.user.id).with_for_update().first()
        if buy_deal is None:
            return restful.params_error(message='未找到可卖批次')
        if buy_deal.s_num < num:
            return restful.params_error(message='剩余转让数量不足')
        print(num)
        buy_deal.s_num -= num
        if buy_deal.s_num < buy_deal.s_num_sell:
            buy_deal.s_num_sell = buy_deal.s_num

        create_deal = BuyDeal(
            sell_order_id=None, buy_order_id=None,
            buyer_id=g.user.id, seller_id=g.user.id,
            sell_batch_id=buy_deal.id, deal_num=num * 2, deal_price=buy_deal.deal_price,
            deal_type=5, deal_money=num * 2 * buy_deal.deal_price, s_num=num*2, s_num_sell=0, tn_day=0,
            goods_id=buy_deal.goods_id, buy_fee=0, sell_fee=0,
            t_type=1, status=0
        )
        db.session.add(create_deal)

        if buy_deal.t_type == 2:
            r_type = 21
        else:
            r_type = 22

        # 明细记录
        api_util.user_record(
            user_id=g.user.id, r_label=10, r_type=r_type, r_state=1,
            num=num * 2, r_wallet=1, order_id=buy_deal.id,
            r_coin=buy_deal.deal_price,
        )
        db.session.commit()

        return restful.success()
    except Exception as e:
        print(e)
        db.session.close()
        return restful.params_error(message='网络错误请重试！')


@bp.route('/buy_deal_today/')
@login_required
def buy_deal_today():
    page = request.args.get('page', default=1, type=int)
    pages = (page - 1) * 50
    bath = BuyDeal.query.filter(
        BuyDeal.create_time >= date.today(),
        BuyDeal.deal_type == 1,
    ).order_by(BuyDeal.create_time.desc()).limit(50).offset(pages)
    bath_list = list()
    for i in bath:
        bath_info = i.buy_deal_json()
        bath_info['deal_num'] = Decimal(i.deal_num)
        bath_info['s_num'] = i.s_num
        bath_info['phone'] = '手机号：1**********'
        bath_info['status_str'] = '正常交易'
        bath_list.append(bath_info)

    data_dict = dict()
    data_dict['buy_deal_list'] = bath_list
    return restful.success(data=data_dict)

